import jwt
from apps.base_app.models import (
    StudentsList,
    SeniorList,
)
from config.constant import (USER_YEAR, DEFAULT_TOKEN_KEY)
from apps.base_app.utils import RestfulResponse
from django.utils.deprecation import MiddlewareMixin


class LoginCheck(MiddlewareMixin):
    def process_request(self, request):
        """
        :return: None 继续传递请求，| 'response' 直接结束请求
        """
        # 不拦截注册和登录还有API接口(之后可以考虑有特殊的权限认证)，TODO 之后尝试在配置文件中配置无需检验的网站！
        # if request.path_info == '/' or request.path_info == '/register/' or request.path_info.startswith('/api/'):
        #     return
        #
        # # token 校验
        # token = request.META.get('HTTP_AUTHORIZATION')
        # # 没有 token
        # if token is None:
        #     return RestfulResponse(403)
        # try:
        #     res = jwt.decode(token, DEFAULT_TOKEN_KEY, algorithms='HS256')
        # except:
        #     return RestfulResponse(403)
        #
        # # 信息有效校验
        # stu_id = res['stu_id']
        # if stu_id[:4] == USER_YEAR:
        #     user = StudentsList.objects.filter(stu_id=stu_id)
        #     # 没有记录的同学和记录但是没有允许注册的同学不允许登录
        #     if not user.first() or not user.first().right:
        #         return RestfulResponse(403)
        #     request.is_root = request.is_senior = False
        # else:
        #     user = SeniorList.objects.filter(stu_id=stu_id)
        #     # 学长表本来计划没有这个限制，现在加上吧...以防冒充学长
        #     if not user.first() or not user.first().right:
        #         return RestfulResponse(403)
        #     request.is_senior = True
        #     request.is_root = user.first().is_root
        # request.user = user.first()


        # 测试
        request.is_root = request.is_senior = True
        request.user = SeniorList.objects.all().first()
